<template>
  <el-checkbox-group
    v-model="selectedIds"
    class="cc-checkbox"
    :disabled="inputDisabled"
    @change="handleChange"
  >
    <el-checkbox
      v-for="item in options"
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>

<script setup>
import { ref, watch, onMounted, inject } from 'vue';
import { useDisabled } from 'element-plus';
import { useRoleStore } from "@/pinia/modules/role";

const emit = defineEmits(['change'])
const props = defineProps({
  prop: String,
});
const formData = inject('formData');
const options = ref([]);
const initializing = ref(false);
const selectedIds = ref([]);
const inputDisabled = useDisabled();
const roleStore = useRoleStore();

const handleChange = (event) => {
  formData.value[props.prop] = selectedIds.value.join(',');
  emit('change', event);
};

watch(() => selectedIds.value, (newVal) => {
  if (initializing.value) return;

  initializing.value = true;
  formData.value[props.prop] = newVal.join(',');
  initializing.value = false;
});

watch(() => formData.value[props.prop], (newVal) => {
  if (initializing.value) return;

  initializing.value = true;
  selectedIds.value = newVal ? newVal.split(',') : [];
  initializing.value = false;
}, {immediate: true});

onMounted(() => {
  const optionList = [];
  roleStore.getRole().then(roles => {
    roles.forEach(role => {
      optionList.push({key: role.id, value: role.name});
    });
    options.value = optionList;
  });
});
</script>

<style scoped>
.cc-checkbox {
  text-align: left;
}
</style>